<template>
  <div class="dialogue">
    <header id="wx-header">
      <!-- 顶部导航栏 右侧按钮 -->
      <div class="other">
        <!-- 前往群详情 -->
        <router-link
          :to="{
            path: '/wechat/dialogue/dialogue-info',
            query: { mid: mid},
          }"
          tag="span"
          class="iconfont icon-chat-group"
          v-if="midInfo.type==2"
        >
        </router-link>
        <!-- 前往个人详情 -->
        <router-link
          :to="{
            path: '/wechat/dialogue/dialogue-detail',
            query: { mid: mid },
          }"
          tag="span"
          class="iconfont icon-chat-friends"
          v-if="midInfo.type==1"
        ></router-link>
      </div>

      <!-- 顶部导航栏标题 -->
      <div class="center">
        <!-- <router-link to="" tag="div"> -->
          <div @click="$router.back()"  class="iconfont icon-return-arrow">
            <span></span>
          </div>
          
        <!-- </router-link> -->
        <div class="dialogue-title-box">
            {{ midNickName }}<span  class="parentheses" v-if="midInfo.type==2" >{{  midNumber }}</span >
            <span v-if="midInfo.type==1 && midInfo.online==1" class="cgreen">[在线]</span>
        </div>


      </div>
    </header>

    <!-- 长按菜单事件 -->
    <section
      class="dialogue-section"
      id="msg-list"
      v-on:click="MenuOutsideClick"
    >

      <div class="system-msg" v-if="finished">没有更多了</div>
      <div class="system-msg" v-if="loading">加载中...</div>
      <!-- 消息列表 -->
      <div  v-for="(item, index) in msgList.list"
        :key="index">
      
      <!-- 普通的对话消息 -->
      <div
        v-if="['1','2'].indexOf(item.type)>-1"
        class="row"
        :class="item.from_user_id == $store.state.uid ? 'right' : ''"
      >
      <!-- 头像展示 -->
        <img :src="item.from_user_headimg" class="header" />
        <div class="msg-box">

          <!-- 右侧展示 -->
          <span v-if="item.from_user_id == $store.state.uid">
            {{ item.create_time | fmtDate("Y-MM-dd hh:mm") }}
           <span v-if="midInfo.type==2">{{ item.from_user_nickname }}</span></span
          >
          <!-- 左侧展示 -->
          <span v-else ><aaa v-if="midInfo.type==2">{{ item.from_user_nickname }}</aaa>
            {{ item.create_time | fmtDate("Y-MM-dd hh:mm") }}</span
          >

          <!-- 图片展示 -->
          <div v-if="item.type == 2" class="msg-image-box">
            <img :src="item.msg" alt="" />
          </div>
          <!-- 文字展示 -->
          <p class="text" v-if="item.type == 1" v-more v-html="parsingEmoji( item.msg)"></p>

        </div>
      </div>
      <!-- 普通对话消息结束 -->

      <!-- 系统提示 -->
      <div class="system-msg" v-if="item.type==3"> 

        <!-- 自己的系统提示 -->
        <span v-if="item.from_user_id == $store.state.uid">你</span>
        <!-- 别人发送的系统提示 -->
        <span v-else>{{item.from_user_nickname}}</span>

        {{item.msg}} 
      </div>

      <!-- 仅自己和对方可见的系统提示 -->
      <div class="system-msg" v-if="item.type==4 && item.from_user_id == $store.state.uid"> 
        <!-- 自己的系统提示 -->
        <!-- <span v-if="item.from_user_id == $store.state.uid">你</span> -->
        <!-- 别人发送的系统提示 -->
        <span>"{{item.from_user_nickname}}"</span>
        {{item.msg}}
      </div>

      </div>

      <!-- 消息列表结束 -->
      <div style="height: 50px">&nbsp;</div>

      <span class="msg-more" id="msg-more">
        <ul>
          <li>复制</li>
          <li>转发</li>
          <li>撤回</li>
          <li>删除</li>
        </ul>
      </span>
    </section>

    <!-- 长按语音事件 -->
    <footer class="dialogue-footer" :class="dialogueFooterClass">
      <div class="component-dialogue-bar-person">
        <span
          class="iconfont icon-dialogue-jianpan"
          v-show="!currentChatWay"
          v-on:click="currentChatWay = true"
        ></span>
        <span
          class="iconfont icon-dialogue-voice"
          v-show="currentChatWay"
          v-on:click="currentChatWay = false"
        ></span>
        <div class="chat-way" v-show="!currentChatWay">
          <!-- v-press -->
          <div class="chat-say" >
            <span class="one">按住 说话</span>
            <span class="two">松开 结束</span>
          </div>
        </div>
        <div class="chat-way" v-show="currentChatWay">

          <!-- <input
            v-model="msgText"
            class="chat-txt"
            type="text"
            v-on:focus="focusIpt"
            v-on:blur="blurIpt"
            @keyup.enter="sendMessage"
          /> -->
          <div class="chat-txt" 
          contenteditable=true 
          placeholder="请输入内容" 
          v-html="parsingEmoji(msgText)" 
          @input="handleInput" 
          @keyup.enter="handleInputClick"
          @click="handleInputClick"
          > </div>
        </div>
        <!-- 表情 -->
        <span class="expression iconfont icon-dialogue-smile" :class="showEmoji?'cgreen':''" @click="clickBtn('emoji')"></span>
        <!-- 更多 加号 -->

        <span
          v-if="msgText == '' || !currentChatWay"
          class="more iconfont icon-dialogue-jia" :class="showJia?'cgreen':''" 
          @click="clickBtn('jia')"
        ></span>

        <span v-else class="more message-btn" @click="sendMessage">发送</span>

        <!-- 语音 取消 发送等 -->
        <div class="recording" style="display: none" id="recording">
          <div
            class="recording-voice"
            style="display: none"
            id="recording-voice"
          >
            <div class="voice-inner">
              <div class="voice-icon"></div>
              <div class="voice-volume">
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
            <p>手指上划,取消发送</p>
          </div>
          <div class="recording-cancel" style="display: none">
            <div class="cancel-inner"></div>
            <p>松开手指,取消发送</p>
          </div>
        </div>
      </div>

      <!-- 底部更多功能 -->
      <div class="footer-more" v-if="showJia">
        <van-uploader :after-read="afterReadImage">
          <div class="footer-more-item">
            <van-icon name="photo-o" />
            <span>相册</span>
          </div>
        </van-uploader>

        <div class="footer-more-item">
          <van-icon name="idcard" />
          <span>文件</span>
        </div>
      </div>

      <!-- 表情 -->
      <div class="footer-more" v-if="showEmoji">
        <Emoji @chooseEmoji="chooseEmoji"/>
      </div>
    </footer>
  </div>
</template>
<script>
import { ApiGetMessageList, ApiSendMessage, ApiSetUp ,ApisetRead} from "@/api/api/message";
import { upImage, upImage2 } from "@/api/api/image";

import { Icon } from "vant";

// 引入表情
// import drawEmoji from "@/utils/emoji/emoji";

import { Uploader } from "vant";

import Emoji from "@/components/emoji2/emoji.vue";


import '@/components/emoji2/emjoymethod'
import '@/components/emoji2/emjoy.css'


export default {
  data() {
    return {
      // pageName: this.$route.query.name,
      currentChatWay: true, //ture为键盘打字 false为语音输入
      timer: null,
      // sayActive: false // false 键盘打字 true 语音输入
      msgInfo: {},
      mid: 0,
      msgText: "", //即将发送的消息
      showJia: false, //是否显示更多功能
      showEmoji:false,//是否显示表情
      // emojiList: [],
      fileList: [], //文件列表

      page: 0, //页码
      scrollTop: 0, //滚动条高度
      loading: false, //是否加载中
      finished: false, //最后一页
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // vm.$store.commit("setPageName", vm.$route.query.name);
    });
  },
  mounted() {
    this.mid = this.$route.query.mid;
    this.init();

    //初始化 回到最后一条记录
    this.toPageEnd();

    this.systemSetUp();//将会话加入到会话列表
  },
  computed: {
    // 聊天消息记录
    msgList() {
      let mid = this.mid;
      return this.$store.state.messageList[mid] || [];
    },
    //当前的用户信息
    midInfo() {
        let wxid = this.mid;
        let {baseMsg} = this.$store.state.msgList;
        let info = {}
        for(let i in baseMsg){
            if(baseMsg[i].mid == wxid){
                info = baseMsg[i]
                break;
            }
        }
        return info
    },
    //当前的聊天对象名称
    midNickName(){
      let midInfo = this.midInfo
      if(midInfo.type==1){
        return midInfo.remark?midInfo.remark:midInfo.getClientMid.nickname
      }else{
        return midInfo?.getUserGroup?.name || '会话列表'
      }
    },
    //聊天对象人数
    midNumber(){
      let midInfo = this.midInfo
      if(midInfo.type==1){
        return 1
      }else{
        return midInfo?.getUserGroup?.member_number || 0
      }
    },
    //底部class
    dialogueFooterClass(){
      if(this.showJia){
        return 'show-more'
      }else if(this.showEmoji){
        return 'show-emoji'
      }
      return ''
    },
  },
  //方法集
  methods: {
    // 初始化获取聊天记录
    init() {
      // 创建监听滚动条事件
      document.getElementById("msg-list").addEventListener("scroll",() => {this.scrollTop = document.getElementById("msg-list").scrollTop},false);

      // 更新vuex 当前聊天对象
      this.$store.commit('setData',{key:'mid',value:this.mid})

      //如果消息记录存在 则无需加载
      if (this.$store.state.messageList[this.mid]) {
        return false;
      }
      //消息记录
      let params = { mid: this.mid};
      ApiGetMessageList(params).then(({ data, msg }) => {
        this.$store.commit("setMessageList", {
          mid: this.mid,
          msgList: data.data,
          page:data.current_page,
        });
        this.toPageEnd();
      });
    },
    //如果是隐藏的会话列表  则释放出来
    systemSetUp(){
      for(let i in this.$store.state.msgList.baseMsg){
        let item = this.$store.state.msgList.baseMsg[i]
        if(item.mid == this.mid){

      // 如果在会话列表隐藏了 那么就将其展示出来
          if(item.is_show==0){
            item.is_show = 1
            let params = {
                mid:this.mid,
                field:'is_show',
                value:1,
            }
            //加入会话列表
            ApiSetUp(params).then(({msg})=>{})
          }
          return ;
        }
      }
    },
    //获取更多的页数
    getMessageList(){
        //已经加载结束  无需加载
        if(this.finished) return;
        //进入加载中 防止重复加载
        if(this.loading) return;
        this.loading = true;

        let page = this.msgList.page
        //消息记录
        let params = { mid: this.mid,page:page+1,pageSize:2 };
        ApiGetMessageList(params).then(({ data, msg }) => {
          // 恢复加载状态
          this.loading = false;
          //加载完成
          if(data.current_page >= data.last_page){
            this.finished = true;
          }
          let oldScrollTop = document.getElementById("msg-list").scrollHeight
          document.getElementById("msg-list").style.overflowY='hidden'
          this.$store.commit("pushMessageInfo", {
            mid: this.mid,
            msgList: data.data,
            page:data.current_page,
          });
          this.toPageEnd(oldScrollTop);
        });
    },
    //界面拉到页尾
    toPageEnd(scrollTop) {
      setTimeout(() => {
        document.getElementById("msg-list").style.overflowY='auto'
        let scrollHeight = document.getElementById("msg-list").scrollHeight
        if(scrollTop){
          scrollHeight = scrollHeight - scrollTop
        }
        document.getElementById("msg-list").scrollTop = scrollHeight;
          

      }, 1);
    },
    //发送文字消息
    sendMessage() {
      this.clickBtn();
      //发送文本消息
      this._sendMessage(this.msgText, 1);
    },

    //上传图片 成功
    afterReadImage(file) {
      let param = new FormData();
      param.append("file", file.file);
      param.append("name", file.name);
      upImage(param).then(({ data, msg }) => {
        //  发送图片消息
        this.showJia = false;

        this._sendMessage(data.file, 2);
      });
    },

    // 给当前的人发送消息
    _sendMessage(msg, type) {
      let params = {
        mid: this.mid,
        msg: msg,
        type: type || 1,
      };
      ApiSendMessage(params).then(({ data, msg }) => {
        this.msgText = ""; //清除消息框
        //发送消息成功 客户端给视图追加消息
        this.$store.commit("addMessageList", {
          mid: this.mid,
          msgList: data,
        });

        // 滚动条 到底部
        // document.documentElement.scrollTop = 9999;
        setTimeout(() => {
          // console.log(document.getElementById('msg-list').scrollTop,'---document.documentElement')
          document.getElementById("msg-list").scrollTop =
            document.getElementById("msg-list").scrollHeight;
          // document.getElementById('msg-list').scrollTop = document.getElementById('myData').scrollHeight;
        }, 10);
      });
    },

    // 解决输入法被激活时 底部输入框被遮住问题
    focusIpt() {
      this.timer = setInterval(function () {
        document.body.scrollTop = document.body.scrollHeight;
      }, 100);
    },
    blurIpt() {
      clearInterval(this.timer);
    },
    // 点击空白区域，菜单被隐藏
    MenuOutsideClick(e) {
      var container = document.querySelectorAll(".text"),
        msgMore = document.getElementById("msg-more");
      if (e.target.className !== "text") {
        msgMore.style.display = "none";
        container.forEach((item) => (item.style.backgroundColor = "#fff"));
      }
    },
    //点击按钮
    clickBtn(type){
      if(type=='jia'){
        this.showEmoji = false
        this.showJia = !this.showJia
      }else if(type=='emoji'){
        this.showEmoji = !this.showEmoji
        this.showJia = false
      }else{
        this.showEmoji = false
        this.showJia = false
      }
    },
    chooseEmoji(e){
      this.msgText += e
    },
    //监听div -input框的输入
    handleInput($event){
      this.msgText = $event.target.innerText;
    },
    handleInputClick(){
      let selection = getSelection()
      this.lastEditRange = selection.getRangeAt(0)
      console.log(selection,this.lastEditRange,'----selection')
    }
  },
  watch: {
    scrollTop(val) {
      // console.log(this.scrollTop,this.loading , this.finished)
      //如果是加载中 或者加载完毕 就不再执行
      if (this.loading || this.finished) {
        return;
      }
      if (this.scrollTop < 10) {
        //加载下一页
        this.getMessageList()
      }
    },
    //监听个人信息
    midInfo(val){
      //如果有未读消息数 修改为已读
      console.log(val.msg_reda_number,'---未读消息数量')
      if(val.msg_reda_number>0){
        let params = {mid:this.mid}
        ApisetRead(params).then(res=>{
          val.msg_reda_number = 0// 更新视图
        })
      }
    }
  },
  components: {
    [Icon.name]: Icon,
    [Uploader.name]: Uploader,
    Emoji,
  },
  // 指令
  directives: {
    press: {
      inserted(element) {
        var recording = document.querySelector(".recording"),
          recordingVoice = document.querySelector(".recording-voice"),
          recordingCancel = document.querySelector(".recording-cancel"),
          // startTx,
          startTy;
        //监听手指长按事件
        element.addEventListener(
          "touchstart",
          function (e) {
            // 用bind时，vue还没插入到dom,故dom获取为 undefine，用 inserted 代替 bind,也可以开个0秒的定时器
            element.className = "chat-say say-active";
            recording.style.display = recordingVoice.style.display = "block";
            var touches = e.touches[0];
            // startTx = touches.clientX
            startTy = touches.clientY;
            e.preventDefault();
          },
          false
        );
        element.addEventListener(
          "touchend",
          function (e) {
            /*var touches = e.changedTouches[0];
                        var distanceY = startTy - touches.clientY;
                        if (distanceY > 50) {
                            console.log("取消发送信息");
                        }else{
                            console.log("发送信息");
                        }*/

            element.className = "chat-say";
            recordingCancel.style.display =
              recording.style.display =
              recordingVoice.style.display =
                "none";
            e.preventDefault();
          },
          false
        );
        element.addEventListener(
          "touchmove",
          function (e) {
            var touches = e.changedTouches[0],
              // endTx = touches.clientX,
              endTy = touches.clientY,
              // distanceX = startTx - endTx,
              distanceY = startTy - endTy;

            if (distanceY > 50) {
              element.className = "chat-say";
              recordingVoice.style.display = "none";
              recordingCancel.style.display = "block";
            } else {
              element.className = "chat-say say-active";
              recordingVoice.style.display = "block";
              recordingCancel.style.display = "none";
            }
            // 阻断事件冒泡 防止页面被一同向上滑动
            e.preventDefault();
          },
          false
        );
      },
    },
    more: {
      bind(element) {
        var startTx, startTy;
        element.addEventListener(
          "touchstart",
          function (e) {
            var msgMore = document.getElementById("msg-more"),
              touches = e.touches[0];
            startTx = touches.clientX;
            startTy = touches.clientY;

            clearTimeout(this.timer);
            this.timer = setTimeout(() => {
              // 控制菜单的位置
              msgMore.style.left =
                (startTx - 18 > 180 ? 180 : startTx - 18) + "px";
              msgMore.style.top = element.offsetTop - 33 + "px";
              msgMore.style.display = "block";
              element.style.backgroundColor = "#e5e5e5";
            }, 500);
          },
          false
        );
        element.addEventListener(
          "touchmove",
          function (e) {
            var touches = e.changedTouches[0],
              disY = touches.clientY;
            if (Math.abs(disY - startTy) > 10) {
              clearTimeout(this.timer);
            }
          },
          false
        );
        element.addEventListener(
          "touchend",
          function () {
            clearTimeout(this.timer);
          },
          false
        );
      },
    },
  },
    destroyed() {
      // 移除vuex 当前聊天对象
      this.$store.commit('setData',{key:'mid',value:0})
 },
};
</script>
<style lang="less">
@import "../../assets/less/dialogue.less";

.say-active {
  background: #c6c7ca;
}
.system-msg{
  text-align: center;
  color: #999;
  margin: 20px 0px;
}
.cgreen{
  color: #058618 !important;;
  font-size: 12px;
}

</style>